package org.mech.sefer.event.register.impl;

import org.mech.sefer.event.Handler;
import org.mech.sefer.event.register.HandlerRegistration;
import org.mech.sefer.event.register.HandlerRegistrationInfo;
import org.mech.sefer.event.register.HandlerRegistry;

/**
 * <p>
 * The HandlerRegistrationImpl is default {@link HandlerRegistration} implementation.
 * </p>
 * <p>
 * Date: 24.4.2012 8:50:10
 * </p>
 *
 * @author martin.krajc
 */
public class HandlerRegistrationImpl implements HandlerRegistration {

	private Handler handler;
	private HandlerRegistry registry;
	private HandlerRegistrationInfo info;
	private boolean registered;

	/**
	 * Instantiates a new handler registration impl.
	 *
	 * @param registry the provided handler registry
	 * @param handler the handler to register
	 * @param info the registration info
	 */
	public HandlerRegistrationImpl(HandlerRegistry registry, Handler handler,
			HandlerRegistrationInfo info) {
		this.handler = handler;
		this.info = info;
		this.registry = registry;
		this.registered = false;
		if (!info.isLazy()) {
			register();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void register() {
		if (!registered) {
			registry.register(handler, info.getOrder());
			registered = true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void unregister() {
		if (registered) {
			registry.unregister(handler);
			registered = false;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isRegistered() {
		return registered;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Handler getHandler() {
		return handler;
	}

}
